# -*- coding: utf-8 -*-

import os
import operator
from typing import Any, Callable, Iterable
from collections import UserDict

import yaml

from contract_market import settings
from contract_market.error.error import NotFoundConfigureError


class Configure(UserDict):
    """  """
    pass


def to_parse(cfg: Iterable):
    """ """
    cfg_obj = Configure()
    for next in cfg:
        cfg_obj.update(next)
    return cfg_obj


class InitConfig:
    """ Load config 
    ::param dirname Configuration File Directory
    ::param file  configuration file
    ::param argv Command function input parameter
    """

    def __init__(self, dirname: str, file: str, key: Callable[[Iterable], Any] = None, argv=None) -> None:
        """ """
        self.file = file
        self.current_path = os.path.join(settings.CONFIG_DIR, dirname, file)
        self._key: Callable[[Iterable], Any] = key or to_parse
        self.argv = argv

    def resolve(self):
        _, type = self.file.split(".")
        try:
            return operator.methodcaller("from_" + type, self.current_path, self._key)(self)
        except AttributeError as e:
            raise NotFoundConfigureError("Not found on the due profile") from e

    def from_yaml(self, path: str, key: Callable[[Iterable], Any]):
        """ """
        with open(path, encoding="utf-8") as f:
            cf = yaml.full_load_all(f.read())
            return key(cf)

    def from_ini(self, path: str, key: Callable[[Iterable], Any]):
        """ """
        print("from_ini")
